package com.taomu.app.zongchouhuli.moudle.index.fragment;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.taomu.app.zongchouhuli.R;
import com.taomu.app.zongchouhuli.entity.BaseChangeResponse;
import com.taomu.app.zongchouhuli.framework.BaseFragment;
import com.taomu.app.zongchouhuli.framework.CommonWebActivity;
import com.taomu.app.zongchouhuli.http.res.ResImportNoticeEntity;
import com.taomu.app.zongchouhuli.http.res.ResLunBoEntity;
import com.taomu.app.zongchouhuli.http.res.ResMainProductListEntity;
import com.taomu.app.zongchouhuli.http.res.ResNoticeEntity;
import com.taomu.app.zongchouhuli.http.res.ResProductEntity;
import com.taomu.app.zongchouhuli.http.res.ResUpdateInfoEntity;
import com.taomu.app.zongchouhuli.moudle.home.activity.HomeProductDetailActivity;
import com.taomu.app.zongchouhuli.moudle.home.activity.HomeProductMoreActivity;
import com.taomu.app.zongchouhuli.moudle.home.activity.HomeSearchActivity;
import com.taomu.app.zongchouhuli.moudle.index.adpter.BaseProductAdp;
import com.taomu.app.zongchouhuli.moudle.index.contract.ProductContract;
import com.taomu.app.zongchouhuli.moudle.index.contract.impl.ProductPresenter;
import com.taomu.app.zongchouhuli.moudle.index.entity.BannerEntity;
import com.taomu.app.zongchouhuli.moudle.index.entity.NoticeEntity;
import com.taomu.app.zongchouhuli.moudle.index.entity.ProductEntity;
import com.taomu.app.zongchouhuli.moudle.login.activity.LoginActivity;
import com.taomu.app.zongchouhuli.utils.DialogShowUtils;
import com.taomu.app.zongchouhuli.utils.LoadingDialog;
import com.taomu.app.zongchouhuli.utils.ParseUtil;
import com.taomu.app.zongchouhuli.utils.StorageHelper;
import com.taomu.app.zongchouhuli.utils.TimeUtils;
import com.taomu.app.zongchouhuli.utils.TokenDialog;
import com.taomu.app.zongchouhuli.utils.banner.BannerNewsWapper;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import static com.taomu.app.zongchouhuli.moudle.home.activity.HomeProductDetailActivity.PRODUCTTYPEID;

/**
 * 产品首页
 */
public class ProductIndexFragment extends BaseFragment<ProductContract.Presenter> implements ProductContract.View {

    private ImageView mSearchIm;

    private Banner mBanner;

    private ViewFlipper mViewFillper;

    private TextView mHotMoreTv;

    private TextView mSuprmeMoreTv;

    private RecyclerView mHotRecy;

    private RecyclerView mSuprmeRecy;

    private BaseProductAdp mHotAdp,mSuprmeAdp;

    private Dialog mDialog;

    private DialogShowUtils showUtils;

    private SmartRefreshLayout mRefreshlayout;

    public static ProductIndexFragment getInstence(){
        return new ProductIndexFragment();
    }

    @Override
    public void onDestroy() {
        mPresenter.onDetch();
        super.onDestroy();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_index_product;
    }

    @Override
    protected void initView(View view) {
        showUtils = new DialogShowUtils();
        mDialog = LoadingDialog.createLoadingDialog(getContext(), "加载中...");
        mRefreshlayout = view.findViewById(R.id.smart_refresh);
        mRefreshlayout.setEnableLoadMore(false);
        mSearchIm = view.findViewById(R.id.product_search_im);
        mBanner = view.findViewById(R.id.product_banner);
        mViewFillper = view.findViewById(R.id.product_filpper);
        mHotMoreTv = view.findViewById(R.id.product_hot_more_tv);
        mHotAdp = new BaseProductAdp(getContext());
        mHotRecy = view.findViewById(R.id.product_hot_recy);
        mHotRecy.setNestedScrollingEnabled(false);
        mHotRecy.setLayoutManager(new LinearLayoutManager(getContext()));
        mHotRecy.setAdapter(mHotAdp);
        mSuprmeMoreTv = view.findViewById(R.id.product_supreme_more_tv);
        mSuprmeAdp = new BaseProductAdp(getContext());
        mSuprmeRecy = view.findViewById(R.id.product_supreme_recy);
        mSuprmeRecy.setNestedScrollingEnabled(false);
        mSuprmeRecy.setLayoutManager(new LinearLayoutManager(getContext()));
        mSuprmeRecy.setAdapter(mSuprmeAdp);
    }

    @Override
    public void onResume() {
        mPresenter.getImportInfo();
        mPresenter.updateApp(String.valueOf(getLocalVersion(getContext())));
        if(mViewFillper != null){
            mViewFillper.startFlipping();
        }
        super.onResume();
    }

    @Override
    protected void initData() {
        //mPresenter.getNoticeInfo();
        mPresenter.getHotInfo();
        mPresenter.getSuprmeInfo();
        mPresenter.getNoticeList();
        mPresenter.getLunboInfo();
    }

    @Override
    protected void initEvent() {
        mRefreshlayout.setOnRefreshListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                if(mViewFillper != null){
                    mViewFillper.stopFlipping();
                    mViewFillper.removeAllViews();
                    mViewFillper.setVisibility(View.INVISIBLE);
                }
                mPresenter.getHotInfo();
                mPresenter.getSuprmeInfo();
                mPresenter.getNoticeList();
                mPresenter.getLunboInfo();
                mPresenter.getImportInfo();
            }
        });
        mHotMoreTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToMore();
            }
        });
        mSuprmeMoreTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToMore();
            }
        });
        mSearchIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), HomeSearchActivity.class);
                startActivity(intent);
            }
        });
        mHotAdp.setProductAdpListener(new BaseProductAdp.ProductAdpListener() {
            @Override
            public void onItemClick(ResMainProductListEntity.DataBean entity) {
                HomeProductDetailActivity.start(getContext(),String.valueOf(entity.getId()));
            }
        });
        mSuprmeAdp.setProductAdpListener(new BaseProductAdp.ProductAdpListener() {
            @Override
            public void onItemClick(ResMainProductListEntity.DataBean entity) {
                HomeProductDetailActivity.start(getContext(),String.valueOf(entity.getId()));
            }
        });
    }

    @Override
    protected ProductContract.Presenter createPresenter() {
        return new ProductPresenter(this);
    }

    @Override
    public void setBannerInfo(List<BannerEntity> entities) {
//        BannerNewsWapper bannerWrapper = new BannerNewsWapper(mBanner);
//        bannerWrapper.setDatas(entities);
    }

    @Override
    public void setFillperInfo(List<NoticeEntity> entities) {
        mViewFillper.removeAllViews();
        for (int i = 0; i < entities.size(); i++) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.filpper_layout, null);
            TextView textView = view.findViewById(R.id.filpper_content_tv);
            textView.setText(entities.get(i).getContent());
            mViewFillper.addView(view);
        }
        mViewFillper.startFlipping();
        mViewFillper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonWebActivity.startWithUrl(getActivity(),"http://www.baidu.com","");
            }
        });
    }

    @Override
    public void setHotInfo(ResMainProductListEntity data) {
        mHotAdp.setData(data.getData());
    }

    @Override
    public void setSuprmeInfo(ResMainProductListEntity data) {
        mSuprmeAdp.setData(data.getData());
        mRefreshlayout.finishRefresh();
    }

    @Override
    public void setNoticeList(final ResNoticeEntity entity) {
        mViewFillper.removeAllViews();
        for (int i = 0; i < entity.getData().size(); i++) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.filpper_layout, null);
            TextView textView = view.findViewById(R.id.filpper_content_tv);
            textView.setText(entity.getData().get(i).getNotice_title());
            mViewFillper.addView(view);
        }
        mViewFillper.startFlipping();
        mViewFillper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = mViewFillper.getDisplayedChild();
                Log.d("dwqdqdwqdq", "index:"+index);
                if(entity != null){
                    if(entity.getData().size()>index){
                        mPresenter.getNoticeContent(String.valueOf(entity.getData().get(index).getId()));
                    }
                }
                //CommonWebActivity.startWithUrl(getActivity(),"http://www.baidu.com","");
            }
        });
        mViewFillper.setVisibility(View.VISIBLE);
    }

    @Override
    public void setNoticeContent(String data) {
        CommonWebActivity.startWithContent(getActivity(),data,"详情");
    }

    @Override
    public void setLunboContent(ResLunBoEntity resProductEntities) {
        List<BannerEntity> entities = new ArrayList<>();
        if(resProductEntities.getData() != null){
            for(int i=0;i<resProductEntities.getData().size();i++){
                ResLunBoEntity.DataBean bean = resProductEntities.getData().get(i);
                BannerEntity entity = new BannerEntity();
                entity.setIcon(bean.getAd_url());
                entity.setUrl(bean.getAd_url());
                entities.add(entity);
            }
        }
        BannerNewsWapper bannerWrapper = new BannerNewsWapper(mBanner);
        bannerWrapper.setDatas(entities);
    }

    @Override
    public void setImportNotice(ResImportNoticeEntity entity) {
        List<String> list = StorageHelper.getImportNotice();
        if(list.size() == 0) {
            list.add(String.valueOf(entity.getData().getId()));
            StorageHelper.saveImportNotice(ParseUtil.toJson(list));
            showImportDialog(entity);
        }else{
            if(list.contains(String.valueOf(entity.getData().getId()))){

            }else{
                list.add(String.valueOf(entity.getData().getId()));
                showImportDialog(entity);
            }
        }
        StorageHelper.saveImportNotice(ParseUtil.toJson(list));
        //showImportDialog(entity);
    }

    @Override
    public void setUpdateApp(final ResUpdateInfoEntity resProductEntities) {
        StorageHelper.saveHttpNewDownload(resProductEntities.getData().getVersion_info().getUpdate_url());
        if(resProductEntities.getData().getIs_new() == 0){
            //0不是新版,提示更新
            View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_update_layout, null);
            final Dialog dialog = new Dialog(getContext());
            final TextView tv1 = view.findViewById(R.id.dialog_cancle_tv);
            tv1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setContentView(view);
            TextView tv = view.findViewById(R.id.dialog_confirm_tv);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    Intent intent = new Intent(Intent.ACTION_VIEW);    //为Intent设置Action属性
                    intent.setData(Uri.parse(resProductEntities.getData().getVersion_info().getUpdate_url())); //为Intent设置DATA属性
                    startActivity(intent);
                }
            });
            dialog.show();
        }
    }

    private void showImportDialog(ResImportNoticeEntity entity){
        final Dialog dialog = new Dialog(getContext());
        dialog.setCanceledOnTouchOutside(false);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_import_layout, null);
        dialog.setContentView(view);
        dialog.show();
        final TextView title = view.findViewById(R.id.dialog_import_title_tv);
        title.setText(entity.getData().getNotice_title());
        final WebView content = view.findViewById(R.id.dialog_improt_tv);
        content.loadData(entity.getData().getNotice_content(),"text/html; charset=UTF-8", null);
        final ImageView close = view.findViewById(R.id.btn_close);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        final TextView confirmTv = view.findViewById(R.id.dialog_import_confirm_tv);
        confirmTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        final TextView time = view.findViewById(R.id.dialog_improt_time);
        if (!TextUtils.isEmpty(entity.getData().getCreate_date())) {
            time.setText(TimeUtils.timeFomart(Long.valueOf(entity.getData().getCreate_date())));
        }
    }

    private void jumpToMore(){
        Intent intent = new Intent(getContext(),HomeProductMoreActivity.class);
        startActivity(intent);
    }

    @Override
    public void setPresenter(ProductContract.Presenter presenter) {

    }

    @Override
    public void onPause() {
        super.onPause();
        if(mViewFillper != null){
            mViewFillper.stopFlipping();
        }
    }

    private int showDialog = 0;

    @Override
    public void showLoadingDialog() {
        if(mDialog.isShowing()){
            showDialog++;
        }else{
            showDialog = 1;
            mDialog.show();
        }
    }

    @Override
    public void dismissLoadingDialog() {
        showDialog--;
        if(showDialog<=0){
            if(mDialog != null){
                LoadingDialog.closeDialog(mDialog);
            }
        }
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showToken() {
        TokenDialog.getInsence(getContext()).show();
    }

    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }
}
